# -*- coding: utf-8 -*-
"""
@File    : qinghai_shengji_czt_policy
@Author  : caojy
"""
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class QinghaiShengjicztPolicy(BaseTaxPolicySpider):
    name = 'qinghai_shengji_czt_policy'

    province = '青海省'
    city = ''
    county = ''
    park = ''
    url = 'https://czt.qinghai.gov.cn/zfxxgk/gz/XWGL_ZC_XZGFXWJ.html'

    def start_requests(self):
        for source, county, url in [
            ['青海省财政厅', '', 'https://czt.qinghai.gov.cn/zfxxgk/gz/XWGL_ZC_XZGFXWJ.html'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item, 'pageNum': '1'})

    def parse_list(self, response, **kwargs):
        meta = response.meta
        crsf = response.xpath("//*[@name='csrfmiddlewaretoken']/@value").get()
        prev_item = meta.get('item')
        for elem in response.xpath(
                "//tr/td[not(@id)]//a[contains(@href, 'id/') or @title]/ancestor::td[string-length(string(.))>=10] | "
                "//div[@class='gz-list-body-item']//span//a[contains(@href, 'htm') or @title]/ancestor::span[string-length(string(.))>=10]"
                ""):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        # if response.meta.get("is_next") is not False:
        current = response.xpath("//span[@class='current']/text()").get()
        print('current', current)
        next = response.xpath("//a[contains(text(), '>>')]/@href").re_first(r"'(\d+)'")
        if current != next:
            data = {
                'csrfmiddlewaretoken': crsf,
                'pageNum': meta['pageNum'],
                'page': next
            }
            yield scrapy.FormRequest(response.url, formdata=data, callback=self.parse_list, meta={'item': prev_item, 'pageNum': next}, dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = '1900-01-01'
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl qinghai_shengji_czt_policy".split())
